package com.lw.leetcode.str.a;

/**
 * str
 * 482. 密钥格式化
 * @Author liw
 * @Date 2021/6/28 10:13
 * @Version 1.0
 */
public class LicenseKeyFormatting {

    public static void main(String[] args) {
        LicenseKeyFormatting test = new LicenseKeyFormatting();

        // S = "5F3Z-2e-9-w", K = 4  "5F3Z-2E9W"
//        String str = "5F3Z-2e-9-w";
//        int k = 4;

        // S = "2-5g-3-J", K = 2  "2-5G-3J"
//        String str = "2-5g-3-J";
//        int k = 2;
        String str = "---";
        int k = 3;

        String s = test.licenseKeyFormatting(str, k);
        System.out.println(s);

    }

    public String licenseKeyFormatting(String S, int K) {
        if (K <= 0) {
            return "";
        }
        char[] chars = S.toCharArray();
        int length = S.length();
        StringBuilder builder = new StringBuilder(length);
        int count = 0;
        for (int i = length - 1; i >= 0; i--) {
            char c = chars[i];
            if (c == '-') {
                continue;
            }
            count++;
            if (c > 96) {
                c -= 32;
            }
            builder.append(c);
            if (count == K) {
                builder.append('-');
                count = 0;
            }
        }
        int l = builder.length();
        if (l > 0 && builder.charAt(l - 1) == '-') {
            builder.deleteCharAt(l - 1);
        }
        return builder.reverse().toString();
    }
}
